﻿package com.sos.ui
{ 
	import com.greensock.data.TweenMaxVars;
	import com.greensock.easing.*;
	import com.greensock.TimelineMax;
	import com.greensock.TweenMax;
	import com.sos.core.game.GamePlayerCard;
	import com.sos.core.game.GameStatus;
	import com.sos.core.Position;
	import com.sos.logging.Logger;
	import flash.display.MovieClip;
	import flash.utils.Dictionary;
	 
    public class Field extends MovieClip 
    { 
		public var clientSide:String;
		public var playerList:Dictionary = new Dictionary();
		public var playArea:PlayArea;
		
	
		public function Field() {
			screen.visible = false;
			malusText.visible = false;
			//setChildIndex(screen, 10);
		} 
		
		public function init(area:PlayArea) {
			playArea = area;
			clientSide = playArea.clientSide;
			var pl:PlayerClip;
			var plc:GamePlayerCard;
			var pList:Vector.<GamePlayerCard>;
			pList = playArea.engine.game.homeTeam.formation.getPlayers(true);
			var i:uint = 0;
			for each (plc in pList) {
				
				pl = new PlayerClip(plc, 'home', playArea);
				playerList[pl.instanceId] = pl;
				if (!plc.position.isSubstitution)
					playArea.timeline.insert(animatePlayerIn(pl, pl.position, i));
				
				//setPlayerToPos(pl, pl.position);
				i++;
				
			}
			
			pList = playArea.engine.game.awayTeam.formation.getPlayers(true);
			i = 0;
			for each (plc in pList) {
				pl = new PlayerClip(plc, 'away', playArea);
				playerList[pl.instanceId] = pl;
				
				if (!plc.position.isSubstitution)
					playArea.timeline.insert(animatePlayerIn(pl, pl.position, i));
				//setPlayerToPos(pl, pl.position);
				i++;
			}
			
			if ((playArea.engine.game.turn < 11) || (playArea.engine.game.turn == 11 && (playArea.engine.game.status == GameStatus.SUBSTITUTION || playArea.engine.game.status == GameStatus.RESOLVE_SUBSTITUTION))) {
				pList = playArea.engine.game.deck.playerCards;
			
				for each (plc in pList) {
					if (plc.position.isSubstitution) {
						Logger.debug("UI > FIELDMC > SUB  FOUND: " + plc.name);
						pl = new PlayerClip(plc, clientSide, playArea);
						playerList[pl.instanceId] = pl;
						Logger.debug("UI > FIELDMC > SUB  FOUND: " + pl.playerName + " as " + pl.position);
						pl.visible = false;
						setPlayerToPos(pl, pl.position);
						
					}
				}
			}
			
			
			
		}
		
		public function activate():void {
			var pl:PlayerClip;
			for each (pl in playerList) {
				pl.init();
				pl.initMods();
				pl.setSideGlow();
			}
		}
				
		public function update() {
			var pl:PlayerClip;
			var plc:GamePlayerCard;
			var pos:Position;
			var pList:Vector.<GamePlayerCard>;
			pList = playArea.engine.game.homeTeam.formation.getPlayers();
			for each (plc in pList) {
				if (!playerList[plc.instanceId.toString()]) {
					//Logger.debug("UI > FIELD > NEW PLAYER FOUND: " + plc.name + " in position " + plc.position.sign);
					pl = new PlayerClip(plc, 'home', playArea);
					playerList[pl.instanceId] = pl;
					setPlayerToPos(pl, pl.position, true, true);
				}
				else {
					//Logger.debug("UI > FIELD > UPDATING: " + plc.name + " in position " + plc.position.sign);
					pl = playerList[plc.instanceId.toString()];
					pl.gamePlayer = plc;
					pl.update();
				}
				
				pos = playArea.engine.game.homeTeam.formation.getPlayerPosition(plc);
				if (pos.sign != pl.position)
					setPlayerToPos(pl, pos.sign, false);
					
				if (pos.isSubstitution) 
					pl.visible = false;
				else 
					pl.visible = true;
			}
			pList = playArea.engine.game.awayTeam.formation.getPlayers();
			for each (plc in pList) {
				if (!playerList[plc.instanceId.toString()]) {
					//Logger.debug("UI > FIELD > NEW PLAYER FOUND: " + plc.name + " in position " + plc.position.sign);
					pl = new PlayerClip(plc, 'away', playArea);
					pl.init()
					playerList[pl.instanceId] = pl;
					setPlayerToPos(pl, pl.position, true, true);
				}
				else {
					//Logger.debug("UI > FIELD > UPDATING: " + plc.name + " in position " + plc.position.sign);
					pl = playerList[plc.instanceId.toString()];
					pl.gamePlayer = plc;
					pl.update();
				}
				
				pos = playArea.engine.game.awayTeam.formation.getPlayerPosition(plc);
				if (pos.sign != pl.position)
					setPlayerToPos(pl, pos.sign, false);
				if (pos.isSubstitution) 
					pl.visible = false;
				else
					pl.visible = true;
			}
			
		}
		
		public function animatePlayerIn(pl:PlayerClip, pos:String, order:uint):TimelineMax {
			var childName:String = pos + "_" + pl.side;
			var targetContainer:CardHolder = CardHolder(getChildByName(childName));
			var sourceContainer:CardHolder;
			
			/*
			//SOURCE = OPP CARDHOLDER
			if (pl.side == playArea.clientSide) {
				sourceContainer = CardHolder(getChildByName(pos + "_" + playArea.oppSide));
			}
			else {
				sourceContainer = CardHolder(getChildByName(pos + "_" + playArea.clientSide));
			}
			*/
			sourceContainer = CardHolder(getChildByName("mf_" + pl.side));
			
			pl.x = targetContainer.x;
			pl.y = targetContainer.y;
			targetContainer.currentPlayerId = pl.instanceId;
			//targetContainer.addChild(pl);
			addChild(pl);
			var tl:TimelineMax = new TimelineMax();
			var delay:Number = 0.25 * order;
			
			//SCALE 0 -> 1
			//tl.insert(TweenMax.from(pl, 1.5, new TweenMaxVars().scale(0).blurFilter(3, 3).x(sourceContainer.x).y(sourceContainer.y).delay(delay).ease(Back.easeOut)));
			//NO SCALE
			//tl.insert(TweenMax.from(pl, 1.5, new TweenMaxVars().blurFilter(7, 0).x(sourceContainer.x).y(sourceContainer.y).delay(delay).ease(Back.easeOut)));
			//FIXED ENTER POINT
			//tl.insert(TweenMax.from(pl, 1.5, new TweenMaxVars().scale(0).blurFilter(3, 3).x(0).y( -320).delay(delay).ease(Back.easeOut)));
			tl.insert(TweenMax.from(pl, 1.5, new TweenMaxVars().scale(0).blurFilter(5, 5).bezier([{x:0, y:210},{x:sourceContainer.x, y:-320}]).delay(delay).ease(Quint.easeIn)));
			return tl;
			
		}
		
		public function setPlayerToPos(pl:PlayerClip, pos:String, swap:Boolean = true, isSubbingIn = false) {
			//Logger.debug("UI > FIELD > Moving " + pl.playerName + " from " + pl.position + " to " + pos);
			
			if (pl.position == 'sub_df' || pl.position == 'sub_mf' || pl.position == 'sub_fw') {
				isSubbingIn = true;
				swap = true;
			}
			
			var childName:String = pos + "_" + pl.side;
			var targetContainer:CardHolder = CardHolder(getChildByName(childName));
			if ((targetContainer.currentPlayerId != '')&&(swap == true))
			{
				var sourceName:String = pl.position + "_" + pl.side;
				var sourceContainer:CardHolder = CardHolder(getChildByName(sourceName));
				
				//sourceContainer.addChild(playerList[targetContainer.currentPlayerId]);
				sourceContainer.currentPlayerId = targetContainer.currentPlayerId;
				playerList[targetContainer.currentPlayerId].x = sourceContainer.x;
				playerList[targetContainer.currentPlayerId].y = sourceContainer.y;
				playerList[targetContainer.currentPlayerId].moveTo(pl.position);
				
				if (isSubbingIn) {
					//Logger.debug("UI > FIELD > Substitution: " + playerList[targetContainer.currentPlayerId].playerName + " is going out");
					removeChild(playerList[targetContainer.currentPlayerId]);
				}
				else
					addChild(playerList[targetContainer.currentPlayerId]);
			}
			pl.x = targetContainer.x;
			pl.y = targetContainer.y;
			targetContainer.currentPlayerId = pl.instanceId;
			//targetContainer.addChild(pl);
			addChild(pl);
			pl.moveTo(pos);
			playArea.restoreFrontObjects();
		}
		
		public function getPlayerAtPos(pos:String, side:String):PlayerClip {
			var childName:String = pos + "_" + side;
			var targetContainer:CardHolder = CardHolder(getChildByName(childName));
			if (targetContainer.currentPlayerId != "")
				return playerList[targetContainer.currentPlayerId];
			else
				return null;
		}
		
		public function animatePlayerToPos(pl:PlayerClip, pos:String, swap:Boolean = true, resetWhenDone:Boolean = true):TimelineMax {
			//Logger.debug("UI > Setting player " + pl.playerName + " to position " + pos);
			var childName:String = pos + "_" + pl.side;
			var targetContainer:CardHolder = CardHolder(this.getChildByName(childName));
			var sourceName:String = pl.position + "_" + pl.side;
			var sourceContainer:CardHolder = CardHolder(this.getChildByName(sourceName));
			var playerArray:Vector.<PlayerClip> = new Vector.<PlayerClip>;
			playerArray.push(pl);
			var tl:TimelineMax = new TimelineMax();
			
			tl.insert(new TweenMax(pl, 1, new TweenMaxVars().bezier([ { x:sourceContainer.x, y:targetContainer.y }, { x:targetContainer.x, y:targetContainer.y } ]).ease(Bounce.easeOut)));
			
			if ((targetContainer.currentPlayerId != '')&&(swap == true))
			{
				tl.insert(new TweenMax(playerList[targetContainer.currentPlayerId], 1, new TweenMaxVars().bezier([{x:targetContainer.x, y:sourceContainer.y},{x:sourceContainer.x, y:sourceContainer.y}]).ease(Bounce.easeOut)));
				playerArray.push(playerList[targetContainer.currentPlayerId]);
			}
			
			if (resetWhenDone) {
				tl.addCallback(restorePlayerPositions, 1.5, new Array(playerArray));
			}
			else {
				tl.addCallback(setPlayerToPos, 1.5, new Array(pl, pos, swap));
			}
			tl.play();
			return tl;
		}
		
		public function restorePlayerPositions(playerArray:Vector.<PlayerClip>):void {
			var pl:PlayerClip;
			var childName:String;
			var targetContainer:CardHolder;
			for each (pl in playerArray) {
				childName = pl.position + "_" + pl.side;
				targetContainer = CardHolder(getChildByName(childName))
				pl.x = targetContainer.x;
				pl.y = targetContainer.y;
			}
		}
		
		public function dispose():void {
			for each (var pl:PlayerClip in playerList) {
				pl.dispose();
				try {
					removeChild(pl); 
				}
				catch (e:Error) {
					
				}
				
				pl = null;
			}
		}
		
		public function printStatus() {
			//trace('CURRENT POSITION: ' + position);
		}
    } 
}